<template>
  <div class="index-manage">
    <div class="content">
      <div class="table-con">
        <div class="right-con">
          <gzryManageTable
            ref="gzryManageTable"
            :source="tableList"
            :disabled="disabled"
            @setEqual="setEqual"
            :needPeopleAssess="needPeopleAssess"
            :needPlusMinusPoints="needPlusMinusPoints">
            <div slot="search" class="search-box">
              <div class="search-left">
                <div class="search-item">
                  <el-select
                    v-model="grainDate"
                    filterable
                    placeholder="请选择"
                    size="small"
                    clearable
                    @change="searchData">
                    <el-option
                      v-for="item in timeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </div>
                <div class="search-item">
                  <div class="item_label" style="min-width: 60px">考核等次:</div>
                  <el-select
                    v-model="searchForm.level"
                    filterable
                    placeholder="请选择"
                    size="small"
                    clearable
                    @change="searchData">
                    <el-option
                      v-for="item in orderOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </div>
              </div>
              <div class="search-right">
                <div class="search-item">考核人数：{{ gradeNumObj.totalNum }}人</div>
                <div class="search-item">
                  <el-input
                    placeholder="请输入内容"
                    v-model.trim="searchForm.name"
                    size="small"
                    clearable
                    @keyup.enter.native="searchData">
                    <el-button slot="append" icon="el-icon-search" @click.stop="searchData"></el-button>
                  </el-input>
                </div>
                <div class="search-item">
                  <el-button type="primary" size="small" @click="submitResult()" v-if="!disabled">确认结果</el-button>
                </div>
              </div>
            </div>
            <div slot="search" class="search-box">
              <div class="search-left">
                <div class="search-item">
                  <el-button type="primary" size="small" icon="el-icon-plus" @click.stop="exportClick">导出</el-button>
                </div>
              </div>
              <div class="search-right">
                <div class="search-item">
                  <div class="info">
                    <div class="info_list">好：{{ gradeNumObj.rank1Num }}人</div>
                    <div class="info_list">较好：{{ gradeNumObj.rank2Num }}人</div>
                    <div class="info_list">一般：{{ gradeNumObj.rank3Num }}人</div>
                    <div class="info_list">较差：{{ gradeNumObj.rank4Num }}人</div>
                    <div class="info_list">不定等次：{{ gradeNumObj.rank6Num }}人</div>
                  </div>
                </div>
              </div>
            </div>
          </gzryManageTable>
        </div>
      </div>
    </div>
    <ReasonDialog
      :resultShow="resultShow"
      menuPermission="unit"
      :goodNumber="gradeNumObj.rank1Num"
      :shouldGoodNumber="gradeNumObj.shouldRank1Num"
      :activeRow="activeRow"
      :result-list="orderOption"
      @close="resultShow = false"
      @sureReason="sureReason"
      v-bind="$attrs" />
    <exportListDialog
      ref="exportListDialog"
      :exportShow="exportShow"
      @close="exportShow = false"
      @onExport="onExport" />
    <XnDialog
      custom-class="collect_dialog"
      :visible.sync="submitShow"
      @close="submitShow = false"
      width="420px"
      title="提示">
      <div>
        <i class="color_warning_dia el-icon-warning"></i>
        确认本季度考核结果？确认后不可再修改
      </div>
      <div class="submit_tips">
        <el-button @click="submitShow = false" size="small">取消</el-button>
        <el-button type="primary" size="small" @click="submitAll">确 定</el-button>
      </div>
    </XnDialog>
  </div>
</template>

<script>
import gzryManageTable from './components/gzryManageTable'
import XnDialog from '@com/xnDialog.vue'
import ReasonDialog from '../components/ReasonDialog'
import exportListDialog from '../components/exportListDialog.vue'
import {
  getQuarterAssessPeriods,
  getAdminQueryAssessResultList,
  exportAssessFinalData,
  adminSubmitAssessRank,
  adminSubmitAssessRankNoLoading,
  adminSubmitAllAssessRank,
} from '@apis/grade.js'
export default {
  name: 'indexManage',
  components: { gzryManageTable, XnDialog, ReasonDialog, exportListDialog },
  props: {},
  data() {
    return {
      oragnList: [],
      searchForm: {
        orgId: JSON.parse(localStorage.getItem('PSKH_USERINFO')).loginPostInfo.orgId,
        userType: '0',
        level: '',
        name: '',
      },
      timeList: [],
      grainDate: '',
      tableList: [],
      gradeNumObj: {
        rank1Num: 0,
        rank2Num: 0,
        rank3Num: 0,
        rank4Num: 0,
        rank5Num: 0,
        rank6Num: 0,
        totalNum: 0,
        shouldRank1Num: 0,
      },
      orderOption: [],
      isAdminSubmit: 0,
      isOrgMakeSure: 0,
      disabled: false,
      content: [],
      exportShow: false,
      resultShow: false,
      activeRow: {},
      activeRank: '',
      timer: null,
      resultTipDiaShow: false,
      submitShow: false,
      btnType: '0',
      menuPermission: 'unit',
      shouldGoodList: [],
      needPeopleAssess: true,
      needPlusMinusPoints: true,
    }
  },
  watch: {
    content: {
      handler(news) {
        this.tableList = news
        const orderOptions = [
          {
            value: '',
            label: '全部',
          },
          {
            value: '1',
            label: '好',
          },
          {
            value: '2',
            label: '较好',
          },
          {
            value: '3',
            label: '一般',
          },
          {
            value: '4',
            label: '较差',
          },
          {
            value: '6',
            label: '不定等次',
          },
        ]
        this.searchForm.level = this.searchForm.level || ''
        this.orderOption = orderOptions
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {},
  created() {
    this.getQuarterAssessPeriods()
  },
  mounted() {},
  methods: {
    initManageData() {
      this.getAdminQueryAssessResultList()
    },
    onRoleChange() {
      this.initManageData()
    },
    getQuarterAssessPeriods() {
      getQuarterAssessPeriods().then(res => {
        if (res.status === 200 && res.data.length) {
          const arr = []
          const data = res.data
          for (let i = 0; i < data.length; i++) {
            arr.push({
              value: i,
              label: data[i].periodName,
              quarter: data[i].quarter,
              year: data[i].year,
            })
          }
          this.grainDate = 0
          this.timeList = arr
          this.initManageData()
        }
      })
    },
    searchData() {
      this.initManageData()
    },
    searchGrainDate() {
      this.initManageData()
    },
    onExport(str) {
      const req = `?assessRank=${this.searchForm.level}&keywords=${this.searchForm.name}&orgId=${
        this.searchForm.orgId
      }&quarter=${this.timeList[this.grainDate].quarter}&queryType=${this.searchForm.userType}&year=${
        this.timeList[this.grainDate].year
      }&containFile=${str}&tenantId=${localStorage.pskh_tenantId}`
      const link = document.createElement('a')
      link.href = exportAssessFinalData(req)
      link.target = 'targetName'
      link.click()
      this.exportShow = false
    },
    getAdminQueryAssessResultList() {
      getAdminQueryAssessResultList({
        assessRank: this.searchForm.level,
        assessType: 'QUARTER',
        keywords: this.searchForm.name,
        month: '',
        orgId: this.searchForm.orgId,
        quarter: this.timeList[this.grainDate].quarter,
        year: this.timeList[this.grainDate].year,
        queryType: this.searchForm.userType,
      }).then(res => {
        this.load = false
        this.needPeopleAssess = res.data.needPeopleAssess
        this.needPlusMinusPoints = res.data.needPlusMinusPoints
        this.content = res.data.userAssessFinalResultResponseVOList
        if (res.data.dataNumResponseVO) {
          this.gradeNumObj = res.data.dataNumResponseVO
        } else {
          this.gradeNumObj = {
            rank1Num: 0,
            rank2Num: 0,
            rank3Num: 0,
            rank4Num: 0,
            rank5Num: 0,
            rank6Num: 0,
            totalNum: 0,
            shouldRank1Num: 0,
          }
        }
        const arr = res.data.userAssessFinalResultResponseVOList.slice(0, res.data.shouldRank1Num)
        arr.forEach(item => {
          this.shouldGoodList.push(item.userId)
        })
        this.isAdminSubmit = res.data.isAdminSubmit
        if (this.isAdminSubmit === 1) {
          this.disabled = true
        } else {
          this.disabled = false
        }
      })
    },
    // 导出
    exportClick() {
      if (this.tableList.length === 0) return
      this.exportShow = true
    },
    sureReason(remark, id, albumList) {
      if (this.menuPermission === 'unit') {
        this.activeRow.adminRemark = remark
      }
      this.activeRow.adminFileShowVOList = albumList
      this.submitAssessRank('reason')
    },
    submitAssessRank(type) {
      let assessRank = this.activeRow.assessRank
      if (type === 'reason') {
        assessRank = this.activeRank
      }
      const param = {
        assessRank: assessRank,
        modifyReason: this.activeRow.adminRemark,
        noteId: this.activeRow.noteId,
        fileShowVOList: this.activeRow.adminFileShowVOList,
        personNum: this.tableList.length,
        userId: this.activeRow.userId,
        userName: this.activeRow.userName,
        quarter: this.timeList[this.grainDate].quarter,
        year: this.timeList[this.grainDate].year,
      }
      if (this.menuPermission === 'unit') {
        if (type === 'reason') {
          adminSubmitAssessRank([param]).then(res => {
            if (res.status === 200) {
              if (!res.message) {
                this.activeRow.assessRank = this.activeRank
                this.resultShow = false
                // this.getAssessFinalResultNum()
                this.getData()
              } else {
                this.$confirm(res.message, '提示', {
                  confirmButtonText: '确定',
                  type: 'warning',
                })
                  .then(() => {
                    this.initManageData()
                  })
                  .catch(() => {})
              }
            }
          })
        } else {
          adminSubmitAssessRankNoLoading([param]).then(res => {
            if (res.status === 200) {
              if (!res.message) {
                // this.getAssessFinalResultNum()
                this.getData()
              } else {
                this.$confirm(res.message, '提示', {
                  confirmButtonText: '确定',
                  type: 'warning',
                  showCancelButton: false,
                })
                  .then(() => {
                    this.initManageData()
                  })
                  .catch(() => {})
              }
            }
          })
        }
      }
    },
    submitResult() {
      let finishFlag = true
      let message = ''
      if (this.menuPermission === 'unit') {
        this.tableList.forEach(item => {
          if (!item.assessRank && item.needAssessRank === 1) {
            finishFlag = false
            message = '请完成所有评价之后再提交结果'
          }
        })
      }
      if (!finishFlag) {
        this.$message.warning(message)
      } else {
        this.submitShow = true
      }
    },
    submitAll() {
      const param = {
        assessRank: this.searchForm.level,
        assessType: 'QUARTER',
        keywords: this.searchForm.name,
        month: '',
        orgId: this.searchForm.orgId,
        quarter: this.timeList[this.grainDate].quarter,
        year: this.timeList[this.grainDate].year,
        queryType: this.searchForm.userType,
        personNum: this.tableList.length,
      }
      adminSubmitAllAssessRank(param).then(res => {
        if (res.status === 200) {
          if (!res.message) {
            this.$message.success('确认成功')
            this.initManageData()
            this.submitShow = false
            this.load = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'warning',
              showCancelButton: false,
            })
              .then(() => {
                this.submitShow = false
              })
              .catch(() => {})
          }
        }
      })
    },
    getData() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.initManageData()
      }, 500)
    },
    reasonDialogShow(row) {
      this.activeRow = JSON.parse(JSON.stringify(row))
      this.activeRank = row.assessRank
      this.resultShow = true
    },
    setEqual(item, row) {
      if (this.disabled) return
      if (
        item.id === '1' &&
        this.gradeNumObj.rank1Num >= this.gradeNumObj.shouldRank1Num &&
        this.menuPermission === 'unit' &&
        row.assessRank !== '1'
      ) {
        this.$message.warning(`根据评分规则，设置等次为好的人数最多为${this.gradeNumObj.shouldRank1Num}人`)
        return
      }

      if (
        (this.menuPermission === 'unit' && !this.shouldGoodList.includes(row.userId) && item.id === '1') ||
        this.menuPermission === 'org'
      ) {
        this.activeRank = item.id
        this.activeRow = JSON.parse(JSON.stringify(row))
        this.resultShow = true
      } else {
        row.adminFileShowVOList = []
        row.adminRemark = ''
        row.assessRank = item.id
        this.activeRow = JSON.parse(JSON.stringify(row))
        this.submitAssessRank()
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@styles/layout.scss';
.index-manage {
  height: 100%;
  padding-top: 15px;
  padding-bottom: 15px;
  .content {
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    .table-con {
      flex: 1;
      display: flex;
      .right-con {
        flex: 1;
        margin: 0 auto;
        position: relative;
        display: flex;
        flex-direction: column;
        width: 100%;
        .search-item {
          display: flex;
          align-items: center;
          .item_label {
            margin-right: 10px;
          }
        }
      }
    }
  }
}
/deep/.dia_con {
  h3,
  p {
    color: #333333 !important;
  }
  p {
    margin-top: 10px;
    margin-bottom: 5px;
  }
  .detail {
    padding-left: 20px;
    span {
      color: #1559b8;
      display: inline-block;
      width: 120px;
      margin-left: 5px;
    }
  }
}
/deep/.submit_tips {
  text-align: center !important;
  margin: 25px 0 10px;
}
.color_warning_dia {
  color: #e6a23c;
  font-size: 18px;
}
</style>
